import axios from "axios";
import Cookie from "js-cookie";

const request = axios.create({
  timeout: 3000,
  timeoutErrorMessage: "请求超时",
});

// 请求拦截
request.interceptors.request.use(
  (config) => {
    if (Cookie.get("token")) {
      config.headers.authorization = Cookie.get("token");
    }

    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

// 响应拦截
request.interceptors.response.use(
  (config) => {
    return config.data;
  },
  (err) => {
    return Promise.reject(err);
  }
);
//中间件集中处理catch
const newRequest = (page: {
  url?: string;
  method?: string;
  data?: any;
  params?: any;
}) => {
  const { url, method = "get", data = {}, params = {} } = page;

  return new Promise((reslove) => {
    request({
      url,
      method,
      data,
      params,
    })
      .then((res) => {
        reslove(res);
      })
      .catch(() => {});
  });
};

export default newRequest;
